<template>
  <div class="template-content">
    <SearchHeader v-model="queryParam.where.keyword" @handleSearch="getData" @handleAdd="add" @handleInit="queryParam.init">
      <Row :gutter="4" >
        <Col span="6"><Input placeholder="菜单编号" v-model="queryParam.where.atCode"></Input> </Col>
        <Col span="6"><Input placeholder="菜单名称" v-model="queryParam.where.atName"></Input> </Col>
        <Col span="6"><AuthorizationTree v-model="queryParam.where.parentId" ref="srhParent" placeholder="上级菜单..."></AuthorizationTree> </Col>
      </Row>
    </SearchHeader>
    <Card>
      <Table row-key="id" :load-data="getChild" ref="table" :columns="columns" :data="tableData" border>
        <template slot-scope="{ row, index }" slot="action">
          <Button type="default" Title="新增下级菜单" icon="ios-add"  style="margin-right: 5px" @click="add(row)"></Button>
          <Button type="default" Title="编辑" icon="md-create" style="margin-right: 5px" @click="edit(row)"></Button>
          <Button type="default" Title="删除" icon="md-trash"  @click="remove(row)"></Button>
        </template>
      </Table>
      <TopnavPage v-model="queryParam.page" @changePage="getData"></TopnavPage>
    </Card>
    <Modal v-model="addModal" :loading="modalLoading" title="新增/修改数据"  @on-ok="addOk"  @on-cancel="cancel" okText="保存"> <!-- footer-hide="false" -->
      <Form :model="rowData" label-position="right" :label-width="80">
        <FormItem label="菜单编号"><Input v-model="rowData.atCode"></Input></FormItem>
        <FormItem label="菜单名称"><Input v-model="rowData.atName"></Input></FormItem>
        <FormItem label="上级菜单"><AuthorizationTree v-model="rowData.parentId" width="200px" ref="edtParent"></AuthorizationTree></FormItem>
      </Form>
    </Modal>
    <AuthorizationEdit ref = "authorizationEdit"></AuthorizationEdit>
  </div>
</template>
<script>
import Authorization from '@/api/Authorization';
import TopnavPage from "_c/topnav/TopnavPage";
import SearchHeader from "@/view/Common/SearchHeader";
import AuthorizationEdit from '@/view/Authorization/AuthorizationEdit';
import AuthorizationTree from '@/view/Authorization/AuthorizationTree';
import {apiResult} from "@/libs/util";
export default {
  name: "Authorization",
  components: {AuthorizationTree,TopnavPage,SearchHeader,AuthorizationEdit},
  data(){
    return{
      api: new Authorization(),
      pageizeOpts:[10,15,20,30,40,100],
      queryParam:{
        page: {
          current: 1,
          desc: ['create_time'],
          maxLimit: 10000,
          optimizeCountSql: true,
          pages: 0,
          searchCount: true,
          size: 15,
          total: 0
        },
        where: {
          keyword: null,
          atCode: null,
          atName: null,
          parentId: null,
          toplayer: false
        },
        init:()=>{
          this.queryParam.where.keyword=null;
          this.queryParam.where.atCode=null;
          this.queryParam.where.atName=null;
          this.queryParam.where.parentId=null;
          this.queryParam.where.toplayer =false;
        }
      },
      rowData: {
        atCode: null,
        id: null,
        atName: null,
        parentId: null,
        parentName: null,
        atPath: null
      },
      columns: [
        { type: 'selection',width: 60},
        { title: '编号', key: 'atCode', sortable: true, width: 355,tree: true },
        { title: '名称', key: 'atName', sortable: false, width: 250 },
        { title: '上级', key: 'parentName', resizable: true,sortable: false, width: 200 },
        { title: '操作', key: 'action', width: 200, slot: 'action'}],
      tableData: [],
      addModal: false,
      modalLoading: false,
    }
  },
  methods: {
    getData() {
      this.tableData=[];

      if (!this.queryParam.where.keyword && !this.queryParam.where.atCode
        && !this.queryParam.where.atName && !this.queryParam.where.parentId){
        this.queryParam.where.toplayer =true
      }else{
        this.queryParam.where.toplayer =false
      }

      this.api.queryToplayerPage(JSON.stringify(this.queryParam)).then(res => {
          apiResult(res.data,false,result=>{
            this.queryParam.page.total = result.data.total;
            let datas = [];
            for (let i in result.data.records) {
              const o = result.data.records[i];
              if (o.hasChild == true) {
                let d = {
                  id: o.id,
                  atCode: o.atCode,
                  atName: o.atName,
                  atPath: o.atPath,
                  parentId: o.parentId,
                  parentName: o.parentName,
                  _loading: false,
                  children: []
                }
                datas.push(d);
              } else {
                let d = {
                  id: o.id,
                  atCode: o.atCode,
                  atName: o.atName,
                  atPath: o.atPath,
                  parentId: o.parentId,
                  parentName:  o.parentName,
                }
                datas.push(d);
              }
              this.tableData = datas;
            }
          })
      })
    },
    initRowData() {
      let rowD =
        {
          id:null,
          atCode: null,
          atName: null,
          parentId: null,
          parentName: null,
          atPath: null
        }
      return  rowD;
    },
    add(row) {
      if (!!row) {
        //下级
        row._showChildren=true;
        this.$refs.authorizationEdit.openDialog("ADD",row,
          (data)=>{
            if (!data){return;}

            let d = {
              id: data.id,
              atCode: data.atCode,
              atName: data.atName,
              atPath: data.atPath,
              parentId: data.parentId,
              parentName: data.parentName,
            }
            if (data.hasChild == true){
              d.children= [];
            }
            let children=[];
            if (!!row.children){
              children=row.children;
            }
            children.push(d);
            row.children = children;
          }
        );
      }else{
        this.$refs.authorizationEdit.openDialog("ADD",this.initRowData(),
          (data)=>{
            if (!data){return;}
            if (!data.parentId){
              this.getData();
            }
          });
      }
    },
    edit(row) {
      console.log(row);
      this.$refs.authorizationEdit.openDialog("EDIT",row,
        (data)=>{
          console.log("row:%o",row);
          console.log("data:%o",data);

          row.atCode = data.atCode;
          row.atName = data.atName;
          row.parentId = data.parentId;
        });
    },
    addOk() {
      /** 新增 */
      //this.rowData.parentId = this.$refs.edtParent.getValue();
      if (this.rowData.id == null) {
        this.api.add(JSON.stringify(this.rowData)).then(res => {
          apiResult(res.data,true,result=>{
            this.getData();
            this.addModal = false;
          },err=>{
            this.modalLoading = false;
            setTimeout(() => {
                this.modalLoading = true;
                 this.addModal = true;
            }, 1000);
          })

        })
      } else {

        this.api.update(JSON.stringify(this.rowData)).then(res => {
          apiResult(res.data,true,result=>{
            this.getData();
            this.addModal = false;
          },err=>{
            this.modalLoading = false;
            setTimeout(() => {
              this.modalLoading = true;
              this.addModal = true;
            }, 1000);
          })
        })
      }
    },
    cancel() {
      this.addModal = false;
    },
    remove(row) {
      this.$Modal.confirm({
        title: '删除确认',
        content: '<p>确定要删除此项？</p',
        onOk:(() => {
          api.remove(JSON.stringify(row)).then(res=>{  //特别注意此 then(res=>...) 误写成 then()(res=>... 报错
            apiResult(res.data,true,result=>{
              this.getData();
            })
          })
        }),
        onCancel: (() => {
        })
      });
    },

    getChild(item, callback) {
      console.log("callback= %o",callback);
      //console.log(item);
      let datas = [];
      this.api.queryChildrens(JSON.stringify({parentId:item.id})).then(res => {
        apiResult(res.data,false,result=>{
          for (let i in result.data) {
            let o = result.data[i];
            if (o.hasChild == true) {
              var d = {
                id: o.id,
                atCode: o.atCode,
                atName: o.atName,
                atPath: o.atPath,
                parentId: o.parentId,
                _loading: false,
                children: [],
                parentName: o.parentName,
              }
              datas.push(d);
            } else {
              var d = {
                id: o.id,
                atCode: o.atCode,
                atName: o.atName,
                atPath: o.atPath,
                parentId: o.parentId,
                parentName: o.parentName,
              }
              datas.push(d);
            }
          }
          callback(datas);
        });
        /*if (res.data.code === 0) {
          for (let i in res.data.data) {
            var o = res.data.data[i];
            if (o.hasChild == true) {
              var d = {
                id: o.id,
                atCode: o.atCode,
                atName: o.atName,
                atPath: o.atPath,
                parentId: o.parentId,
                _loading: false,
                children: [],
                parentName: o.parentName,
              }
              datas.push(d);
            } else {
              var d = {
                id: o.id,
                atCode: o.atCode,
                atName: o.atName,
                atPath: o.atPath,
                parentId: o.parentId,
                parentName: o.parentName,
              }
              datas.push(d);
            }
          }
          callback(datas);
          console.log(datas);
        }*/

      });

    },
  },
  mounted (){
    this.getData();
  },
}

</script>
<style lang="less">
@import ".././template";
@import "../style/view-table";
.ivu-table .error td{
  color: red;
}
.expand-key {
  font-weight: bold;
}
.action-style{
  width: 50px;
  height: 30px;
  borderRadius: 5px
}
</style>
